#!/usr/bin/env python3
"""
acpid MCP Server

面向 acpid (Advanced Configuration and Power Interface event daemon) 软件的命令行操作。
提供对 acpid 和 acpi_listen 命令行工具的封装。

MCP tools 列表：
1. acpid_version - 显示 acpid 版本信息
2. acpid_help - 显示 acpid 帮助信息  
3. acpid_foreground - 在前台运行 acpid
4. acpid_logevents - 启用事件日志功能运行 acpid
5. acpid_debug - 启用调试模式运行 acpid
6. acpi_listen_version - 显示 acpi_listen 版本信息
7. acpi_listen_help - 显示 acpi_listen 帮助信息

所有 tool 返回统一 JSON 结构：
{
  "success": bool,      # 命令是否成功执行
  "command": str,       # 实际执行的命令行
  "exit_code": int,     # 进程退出码
  "stdout": str,        # 标准输出内容
  "stderr": str         # 标准错误内容
}
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import shlex

mcp = FastMCP("acpid MCP Server")

@mcp.tool()
def acpid_version(ctx: Context) -> dict:
    """
    显示 acpid 版本信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpid -v"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpid_help(ctx: Context) -> dict:
    """
    显示 acpid 帮助信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpid -h"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpid_foreground(ctx: Context) -> dict:
    """
    在前台运行 acpid（使用 -f 选项）
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpid -f"
    try:
        # 使用 timeout 限制执行时间，避免长时间阻塞
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=5)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        # 超时是预期的，因为 -f 选项会保持运行
        return {
            "success": True,
            "command": cmd,
            "exit_code": 0,
            "stdout": "acpid started in foreground (process terminated due to timeout)",
            "stderr": ""
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpid_logevents(ctx: Context) -> dict:
    """
    启用事件日志功能运行 acpid（使用 -l 选项）
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpid -lf"
    try:
        # 使用 timeout 限制执行时间
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=5)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": True,
            "command": cmd,
            "exit_code": 0,
            "stdout": "acpid started with event logging (process terminated due to timeout)",
            "stderr": ""
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpid_debug(ctx: Context) -> dict:
    """
    启用调试模式运行 acpid（使用 -d 选项）
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpid -df"
    try:
        # 使用 timeout 限制执行时间
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=5)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": True,
            "command": cmd,
            "exit_code": 0,
            "stdout": "acpid started in debug mode (process terminated due to timeout)",
            "stderr": ""
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpi_listen_version(ctx: Context) -> dict:
    """
    显示 acpi_listen 版本信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpi_listen -v"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def acpi_listen_help(ctx: Context) -> dict:
    """
    显示 acpi_listen 帮助信息
    
    返回:
        dict: 包含命令执行结果的 JSON 对象
    """
    cmd = "acpi_listen -h"
    try:
        result = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()